/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dal;

import Util.HibernateUtil2;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Users;

/**
 *
 * @author Sy Dai
 */
public class user {

    public user() {
    }

    public static boolean login(Users us) {
        Session session = (Session) HibernateUtil2.getSessionFactory();
        try {
            String str_login_query = "select id from users where email='" + us.getEmail().trim() + "' and password='" + MD5(us.getPassword());
            Query query = session.createQuery(str_login_query);
            List lst_login = query.list();
            if (!lst_login.isEmpty()) {
                return true;
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            session.close();
        }
        return false;
    }

    public static boolean register(Users us) {

        Session session = HibernateUtil2.getSessionFactory().openSession();
        Transaction transaction = null;
        List lst_user = null;
        try {
            transaction = session.beginTransaction();
            session.save(lst_user);
            transaction.commit();
        } catch (HibernateException ex) {
            //Ghi loi vao file Log su dung Log4J
            transaction.rollback();
            throw new HibernateException(ex.toString());
        } finally {
            session.close();
        }
        return true;
    }

    public static boolean update_profile(Users us) {
        Session session = HibernateUtil2.getSessionFactory().openSession();
        Transaction transaction = null;
        List lst_user = null;
        try {
            transaction = session.beginTransaction();
            session.update(lst_user);
            transaction.commit();
        } catch (HibernateException ex) {
            transaction.rollback();
            throw new HibernateException(ex.toString());
        } finally {
            session.close();
        }
        return true;
    }

    public static String MD5(String str_input) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(str_input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

}
